<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="关键词" prop="keyword">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入关键词"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="一级类目" prop="firstLevelColumn">
        <!-- <el-input v-model="queryParams.firstLevelColumn" placeholder="请输入一级类目" clearable
          @keyup.enter.native="handleQuery" /> -->
        <el-select
          v-model="queryParams.firstLevelColumn"
          placeholder="请选择一级类目"
          clearable
        >
          <el-option
            v-for="dict in dict.type.sys_product_pl"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="尺码表图片" prop="sizeUrl">
        <el-input v-model="queryParams.sizeUrl" placeholder="请输入尺码表图片" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:customsize:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:customsize:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:customsize:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:customsize:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="customsizeList"
      @selection-change="handleSelectionChange"
      @row-dblclick="t"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="id" align="center" prop="id" /> -->
      <el-table-column label="关键词" align="center" prop="keyword" />
      <el-table-column
        label="一级类目"
        align="center"
        prop="firstLevelColumn"
      />
      <!-- <el-table-column label="尺码表图片" align="center" prop="sizeUrl" /> -->
      <el-table-column label="尺码表图片" align="center" prop="sizeUrl">
        <template #default="scope">
          <image-preview :src="scope.row.sizeUrl" :width="80" :height="80" />
          <!-- <el-popover
            effect="light"
            trigger="click"
            placement="left"
            width="auto"
            v-show="scope.row.sizeUrl"
          >
            <template #default>
              <img
                :src="pjtUrl + scope.row.sizeUrl"
                style="width: 800px; height: 600px; object-fit: contain"
              />
            </template>
            <template #reference>
              <img
                :src="pjtUrl + scope.row.sizeUrl"
                style="width: 100px; height: 100px; object-fit: contain"
              />
            </template>
          </el-popover> -->
        </template>
        <!-- <template slot-scope="scope">
                                                                  <el-image style="width: 100px; height: 100px" :src="scope.row.logoFullUrl"></el-image></template> -->
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:customsize:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:customsize:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改客服尺码数据字典对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
      v-if="open"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="关键词" prop="keyword">
          <el-input v-model="form.keyword" placeholder="请输入关键词" />
        </el-form-item>
        <el-form-item label="一级类目" prop="firstLevelColumn">
          <!-- <el-input v-model="form.firstLevelColumn" placeholder="请输入一级类目" /> -->
          <el-select
            v-model="form.firstLevelColumn"
            placeholder="请选择一级类目"
            clearable
          >
            <el-option
              v-for="dict in dict.type.sys_product_pl"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="尺码表图片" prop="sizeUrl">
          <!-- <el-input v-model="form.sizeUrl" placeholder="请输入尺码表图片" /> -->
          <el-upload
            ref="uploadPic"
            :action="imgUpload.url"
            :headers="imgUpload.headers"
            list-type="picture-card"
            :on-change="changePic"
            :file-list="filePic"
            multiple
            :on-success="uploadPic"
            :on-remove="RemovePic"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <div id="preview" @paste="handlePic">
            <span
              ><i class="el-icon-s-opportunity" style="color: #fb894c"></i
              >点击此处 将图片按Ctrl+V 粘贴至此处</span
            >
          </div>
        </el-form-item>
        <!-- <el-form-item label="尺码表图片" prop="purchasingAfterPicurl" label-width="40">
          <el-upload :action="imgUpload.url" :headers="imgUpload.headers" list-type="picture-card" :limit="limit"
            :on-exceed="handleExceed" :on-success="handlePictureSuccessPic" :before-upload="beforeAvatarUpload"
            :on-preview="handlePictureCardPreview" :file-list="fileList" :on-change="changeFile2">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" v-if="purchasingAfterPicurl" :src="pjtUrl + purchasingAfterPicurl" alt="">
          </el-dialog>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCustomsize,
  getCustomsize,
  delCustomsize,
  addCustomsize,
  updateCustomsize,
} from "@/api/data/size";
import { getToken } from "@/utils/auth";
export default {
  name: "Customsize",
  dicts: [
    "sys_product_qudao",
    "sys_product_size",
    "sys_product_design",
    "sys_product_scene",
    "sys_product_coder",
    "sys_product_yf",
    "sys_product_cycle",
    "sys_product_pl",
  ],
  data() {
    return {
      picurl: "",
      filePic: [],
      upload_Pic: [], //提交的图片数组

      purchasingAfterPicurl: "",

      pjtUrl: process.env.VUE_APP_BASE_API,
      // 图片数量限制
      limit: 2,
      //页面上存的暂时图片地址List
      // files: [{ url: "" }],
      files: [],
      fileList: [],
      dialogVisible: false,
      imgUpload: {
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        // 图片上传的方法地址:
        url: process.env.VUE_APP_BASE_API + "/common/upload",
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客服尺码数据字典表格数据
      customsizeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        keyword: null,
        firstLevelColumn: null,
        sizeUrl: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        keyword: [
          { required: true, message: "关键词不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //点击某一行
    t(row, column, cell, event) {
      console.log(row, column, cell, event);

      this.handleUpdate(row);
    },
    /** 查询客服尺码数据字典列表 */
    getList() {
      this.loading = true;
      listCustomsize(this.queryParams).then((response) => {
        this.customsizeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        keyword: null,
        firstLevelColumn: null,
        sizeUrl: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加客服尺码数据字典";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;

      getCustomsize(id).then((response) => {
        //图片回显
        this.picurl = response.data.sizeUrl;
        // this.logoUrl = response.data.logoUrl;
        this.filePic = response.data.sizeUrl
          ? [{ url: process.env.VUE_APP_BASE_API + response.data.sizeUrl }]
          : []; //图片加的是这一行
        // this.filelogourl = response.data.logoUrl
        //   ? [{ url: process.env.VUE_APP_BASE_API + response.data.logoUrl }]
        //   : []; //logo图片加的是这一行
        this.form = response.data;
        this.open = true;
        this.title = "修改客服尺码数据字典";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.sizeUrl = this.picurl;
      // this.form.sizeUrl = this.purchasingAfterPicurl;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateCustomsize(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCustomsize(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除客服尺码数据字典编号为"' + ids + '"的数据项？')
        .then(function () {
          return delCustomsize(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "product/customsize/export",
        {
          ...this.queryParams,
        },
        `customsize_${new Date().getTime()}.xlsx`
      );
    },
    //图片上传前的相关判断
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type == "image/png";
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 5MB!");
      }
      return isJPG && isLt2M;
    },
    //图片预览
    handlePictureCardPreview(file) {
      this.purchasingBeforePicurl = file.url;
      this.purchasingAfterPicurl = file.url;
      // this.imageUrl = file.url;
      this.dialogVisible = true;
    },
    handlePictureSuccessPic(res, file) {
      this.purchasingAfterPicurl = file.response.fileName;
    },
    //图片修改前的回调
    handlePictureSuccess(res, file) {
      //设置图片访问路径 （url 后台传过来的的上传地址）
      // this.imageUrl = file.response.url;
      // const url = file.response.fileName;
      this.purchasingBeforePicurl = file.response.fileName;
      // console.log(JSON.stringify(url));
    },

    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传链接LOGO图片数量不能超过 ${this.limit} 个!`);
    },
    changeFile1(file, fileList) {
      if (fileList.length > 1) {
        this.files = fileList.slice(-1);

        // this.fileList = [fileList[fileList.length - 1]]//这一步，是 展示最后一次选择文件
      }
      // this.fileSpecial = fileList;
    },
    changeFile2(file, fileList) {
      if (fileList.length > 1) {
        this.fileList = fileList.slice(-1);

        // this.fileList = [fileList[fileList.length - 1]]//这一步，是 展示最后一次选择文件
      }
      // this.fileSpecial = fileList;
    },
    handlePic(event) {
      const items = (event.clipboardData || window.clipboardData).items;
      let file = null;
      if (!items || items.length === 0) {
        this.$message.error("当前浏览器不支持本地");
        return;
      }
      // 搜索剪切板items
      for (let i = 0; i < items.length; i++) {
        if (items[i].type.indexOf("image") !== -1) {
          file = items[i].getAsFile();
          break;
        }
      }
      if (!file) {
        this.$message.error("粘贴内容非图片");
        return;
      }
      if (this.filePic.length >= this.limit) {
        this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`); // 图片数量超出
        return;
      }
      this.$refs.uploadPic.handleStart(file); // 将粘贴过来的图片加入预上传队列
      this.$refs.uploadPic.submit(); // 提交图片上传队列
    },
    //上传
    changePic(file, fileList) {
      // this.fileList = fileList
      console.log("成功", file, fileList, this.filePic);
      console.log(JSON.stringify(file));
      console.log(JSON.stringify(fileList));
      if (fileList.length > 1) {
        this.filePic = fileList.slice(-1);
      }
    },
    RemovePic() {
      this.picurl = "";
    },
    uploadPic(res, file, fileList) {
      console.log(JSON.stringify(file.response.fileName));
      this.picurl = file.response.fileName;
    },
  },
};
</script>
